using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using CodeStory.News.ObjectEntity;
using CodeStory.Core.UI;
using Activa.CoolStorage;
using CodeStory.Core;

namespace CodeStory.WebApplication.Modules.News.Admin
{
	[NavigationPortlet("CodeStory_News_Admin_CreateNews")]
	public partial class CreateNews : Portlet
	{
		protected override void OnInit(EventArgs e) {
			Load += new EventHandler(CreateNews_Load);
			btnCreate.Click += new EventHandler(ButtonCreate_Click);
			base.OnInit(e);
		}

		void ButtonCreate_Click(object sender, EventArgs e) {
			//throw new Exception("The method or operation is not implemented.");
			NewsContentObject obj;
			string newsid = Request.QueryString["newsid"];
			if (string.IsNullOrEmpty(newsid)) {
				obj = NewsContentObject.New();
				obj.NewsID = Guid.NewGuid();
			} else {
				obj = NewsContentObject.Read(new Guid(newsid));
			}
			obj.NewsTitle = txtTitle.Text;
			obj.NewsSummary = txtSummary.Text;
			obj.NewsContent = txtContent.Text;
			obj.Author = UserContext.Current.UserName;
			obj.CategoryID = new Guid(dpdCategory.SelectedValue);
			obj.PostDate = DateTime.Now;
			obj.Save();
		}

		void CreateNews_Load(object sender, EventArgs e) {
			//throw new Exception("The method or operation is not implemented.");
			if (!IsPostBack) {
				BindCategory();
				BindNewsContent();
			}
		}

		private void BindCategory() {
			//throw new Exception("The method or operation is not implemented.");
			CSList<NewsCategoryObject> list = NewsCategoryObject.List();
			dpdCategory.DataSource = list;
			dpdCategory.DataTextField = "CategoryName";
			dpdCategory.DataValueField = "CategoryID";
			dpdCategory.DataBind();
		}

		private void BindNewsContent() {
			string newsid = Request.QueryString["newsid"];
			if (string.IsNullOrEmpty(newsid)) return;
			NewsContentObject obj = NewsContentObject.Read(new Guid(newsid));
			SelectCategoryItem(obj.CategoryID.ToString());
			txtTitle.Text = obj.NewsTitle;
			txtSummary.Text = obj.NewsSummary;
			txtContent.Text = obj.NewsContent;
		}

		void SelectCategoryItem(string categoryid) {
			foreach (ListItem item in dpdCategory.Items) {
				if (item.Value.Equals(categoryid, StringComparison.OrdinalIgnoreCase)) {
					item.Selected = true;
					break;
				}
			}
		}
	}
}